package LeetCode.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: leiwenkang
 * @Date: 2020/8/13 23:08
 * @Description:
 */
public class Test350两个数组的交集2 {
    //方法一 哈希表
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }

        Map<Integer, Integer> map = new HashMap<>();

        for (int num : nums1) {
            map.putIfAbsent(num, 0);
            map.put(num, map.get(num) + 1);
        }
        int[] intersects = new int[nums1.length];

        int index = 0;
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                intersects[index++] = num;
                map.put(num, count - 1);
            }
        }
        return Arrays.copyOfRange(intersects, 0, index);
    }
}